package com.elitel.frame.base.controller;

import com.elitel.frame.base.component.quartz.QuartzScheduler;
import com.elitel.frame.base.service.*;
import com.elitel.frame.main.entity.*;
import com.elitel.frame.main.entity.ext.BaseQueryfieldExt;
import com.elitel.frame.main.entity.vo.JsonDataResult;
import com.elitel.frame.main.entity.vo.PageRequestVo;
import com.elitel.frame.main.entity.vo.PageResponseVo;
import com.elitel.frame.main.entity.vo.QueryFieldVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author guoyanfei
 * @Description 配置查询字段接口控制
 */
@Controller
@RequestMapping("/system/queryfield")
public class BaseQueryfieldController {
    private static final Logger logger = LoggerFactory.getLogger(BaseQueryfieldController.class);
    @Autowired
    private CfgExtendService cfgExtendService;
    @Autowired
    private CfgExtmasterService cfgExtmasterService;
    @Autowired
    private BaseQueryfieldService baseQueryfieldService;
    @Autowired
    private BaseQuerysqlService baseQuerysqlService;
    @Autowired
    private TreeConfigFileService treeConfigService;
    @Autowired
    private QuartzScheduler quartzScheduler;

    /**
     * @return QueryFieldVo实体
     * @description 查询所有配置表的字段
     * @author guoyanfei
     */
    @RequestMapping("/getAllField")
    @ResponseBody
    public List<QueryFieldVo> getAllField(HttpServletRequest request) {
        List<QueryFieldVo> queryFieldVos = new ArrayList<>();
        try {
            String serviceId = request.getParameter("serviceId");
            String serviceType = request.getParameter("serviceType");
            String grade = request.getParameter("grade");
            String dtConfigId = "";
            if (serviceType.equals("1")) {//单表服务
                CfgExtend cfgExtend = cfgExtendService.selectByPrimaryKey(serviceId);
                if (cfgExtend != null) {
                    dtConfigId = cfgExtend.getDtConfigId();
                }
            } else if (serviceType.equals("2")) {//主从表服务
                CfgExtmaster cfgExtmaster = cfgExtmasterService.getCfgExtmasterByguid(serviceId);
                if (cfgExtmaster != null) {
                    dtConfigId = cfgExtmaster.getDtConfigId();
                }
            } else if (serviceType.equals("3")) {
                BaseTreeconfig baseTreeconfig = treeConfigService.selectTreeConfigOne(serviceId, grade);
                if (baseTreeconfig != null) {
                    dtConfigId = baseTreeconfig.getDtConfigId();
                }
            }
            queryFieldVos = baseQueryfieldService.getAllFieldBydtConfigId(dtConfigId);

            //除去已选字段
			/*List<BaseQueryfield> baseQueryfields = baseQueryfieldService.getQueryFieldByServiceId(serviceId, serviceType);
			if(baseQueryfields != null){
				for (BaseQueryfield baseQueryfield : baseQueryfields) {
					for (QueryFieldVo queryFieldVo : queryFieldVos) {
						if(baseQueryfield.getFieldaddonsguid().equals(queryFieldVo.getFieldguid())){
							queryFieldVos.remove(queryFieldVo);
							break;
						}
					}
				}
			}*/
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return queryFieldVos;
    }

    @RequestMapping("/getAllFieldForSetCondtion")
    @ResponseBody
    public List<QueryFieldVo> getAllFieldForSetCondition(HttpServletRequest request) {
        List<QueryFieldVo> queryFieldVos = new ArrayList<>();
        List<BaseQueryfield> baseQueryFieldList = new ArrayList<>();
        try {
            String serviceId = request.getParameter("serviceId");
            String serviceType = request.getParameter("serviceType");
            String grade = request.getParameter("grade");
            String dtConfigId = "";
            if (serviceType.equals("1")) {//单表服务
                CfgExtend cfgExtend = cfgExtendService.selectByPrimaryKey(serviceId);
                if (cfgExtend != null) {
                    dtConfigId = cfgExtend.getDtConfigId();
                }
            } else if (serviceType.equals("2")) {//主从表服务
                CfgExtmaster cfgExtmaster = cfgExtmasterService.getCfgExtmasterByguid(serviceId);
                if (cfgExtmaster != null) {
                    dtConfigId = cfgExtmaster.getDtConfigId();
                }
            } else if (serviceType.equals("3")) {
                BaseTreeconfig baseTreeconfig = treeConfigService.selectTreeConfigOne(serviceId, grade);
                if (baseTreeconfig != null) {
                    dtConfigId = baseTreeconfig.getDtConfigId();
                }
            }
            queryFieldVos = baseQueryfieldService.getAllFieldBydtConfigId(dtConfigId);

            // here is convert QueryFieldVo into BaseQueryfield type
            queryFieldVos.forEach(queryFieldVo -> {
                // here is add column
                // 			String strFields = request.getParameter("strFields");
                // String serviceId = request.getParameter("serviceId");
                // String serviceType = request.getParameter("serviceType");
                // String grade = request.getParameter("grade");
                // String paramType = request.getParameter("paramType");
                //queryFieldVo.setParametercode(dtConfigId);

                // here is not need my decide can auto save

            });
            // here add need proper field into QueryFieldVo to support page


            //除去已选字段
			/*List<BaseQueryfield> baseQueryfields = baseQueryfieldService.getQueryFieldByServiceId(serviceId, serviceType);
			if(baseQueryfields != null){
				for (BaseQueryfield baseQueryfield : baseQueryfields) {
					for (QueryFieldVo queryFieldVo : queryFieldVos) {
						if(baseQueryfield.getFieldaddonsguid().equals(queryFieldVo.getFieldguid())){
							queryFieldVos.remove(queryFieldVo);
							break;
						}
					}
				}
			}*/

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return queryFieldVos;
    }


    @RequestMapping("updateQueryfield_copy")
    @ResponseBody
    public Integer updateQueryfield_copy(@RequestBody BaseQueryfield baseQueryfield) {
        Integer result = 0;
        try {
            result = baseQueryfieldService.updateQueryfield(baseQueryfield);
            //刷新任务调度
            quartzScheduler.refreshJobTime(baseQueryfield.getServiceid());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * @param request
     * @description 新增查询字段
     * @author guoyanfei
     */
    @RequestMapping("/addQueryField")
    @ResponseBody
    public void addQueryField(HttpServletRequest request) {
        try {
            String strFields = request.getParameter("strFields");
            String serviceId = request.getParameter("serviceId");
            String serviceType = request.getParameter("serviceType");
            String grade = request.getParameter("grade");
            String paramType = request.getParameter("paramType");
            Integer serviceTypeInteger = serviceType != null ? Integer.parseInt(serviceType) : null;
            Integer paramTypeInteger = paramType != null ? Integer.parseInt(paramType) : null;
            baseQueryfieldService.insertBaseQueryfield(strFields, serviceId, serviceTypeInteger, grade, paramTypeInteger);
            //刷新任务调度
            quartzScheduler.refreshJobTime(serviceId);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @RequestMapping("/batchAddQueryFieldBatch")
    @ResponseBody
    public void batchAddQueryField(HttpServletRequest request, @RequestBody List<BaseQueryfield> baseQueryFieldList) {
        try {
            String paramType = request.getParameter("paramType");
            //baseQueryfieldService.insertBaseQueryfield(strFields, serviceId, serviceType,grade,paramType);
            Integer paramTypeInteger = paramType != null ? Integer.parseInt(paramType) : null;
            baseQueryfieldService.addBaseQueryfieldBySqlConditionType(baseQueryFieldList, paramTypeInteger);
            //刷新任务调度
            //quartzScheduler.refreshJobTime(serviceId);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }


    /**
     * @param request
     * @return
     * @description 通过分页显示查询字段列表
     */
    @RequestMapping("/getQueryFieldListPage")
    @ResponseBody
    public PageResponseVo<BaseQueryfield> getQueryFieldListPage(HttpServletRequest request) {
        PageResponseVo<BaseQueryfield> baseQueryfields = new PageResponseVo<BaseQueryfield>();
        try {
            String serviceId = request.getParameter("serviceId");
            String serviceType = request.getParameter("serviceType");
            int pageNo = Integer.parseInt(request.getParameter("pageNo"));
            int pageSize = Integer.parseInt(request.getParameter("pageSize"));
            Integer serviceTypeInteger = serviceType != null ? Integer.parseInt(serviceType) : null;
            PageRequestVo<BaseQueryfield> pr = new PageRequestVo<BaseQueryfield>();
            pr.setPageNo(pageNo);
            pr.setPageSize(pageSize);
            baseQueryfields = baseQueryfieldService.getListByPage(pr, serviceId, serviceTypeInteger);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return baseQueryfields;
    }

    /**
     * @param request
     * @return BaseQueryfieldExt实体
     * @description 通过服务ID和服务类型查询服务查询字段信息
     * @author guoyanfei
     * @date 2017/11/16
     */
    @RequestMapping("/getQueryFieldList")
    @ResponseBody
    public List<BaseQueryfieldExt> getQueryFieldList(HttpServletRequest request) {
        List<BaseQueryfieldExt> baseQueryfieldExts = new ArrayList<BaseQueryfieldExt>();
        try {
            String serviceId = request.getParameter("serviceId");
            String serviceType = request.getParameter("serviceType");
            String grade = request.getParameter("grade");
            String paramType = request.getParameter("paramType");
            Integer paramTypeInt = paramType != null ? Integer.valueOf(paramType) : null;
            baseQueryfieldExts = baseQueryfieldService.getQueryFieldListByServiceId(serviceId, serviceType, grade, paramTypeInt);
            baseQueryfieldService.selectQueryFiled(serviceId,baseQueryfieldExts);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return baseQueryfieldExts;
    }

    /**
     * @param request
     * @return
     * @description 批量删除查询字段信息表数据
     * @author guoyanfei
     */
    @RequestMapping("/deleteQueryfield")
    @ResponseBody
    public Integer deleteQueryfield(HttpServletRequest request) {
        Integer result = 0;
        try {
            String guids = request.getParameter("guids");
            String serviceId = request.getParameter("serviceId");
            result = baseQueryfieldService.deleteQueryfield(guids);
            //刷新任务调度
            quartzScheduler.refreshJobTime(serviceId);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return result;
    }

    /**
     * @param baseQueryfield
     * @return 修改结果
     * @description 修改查询字段信息
     * @author guoyanfei
     */
    @RequestMapping("updateQueryfield")
    @ResponseBody
    public Integer updateQueryfield(@RequestBody BaseQueryfield baseQueryfield) {
        Integer result = 0;
        try {
            result = baseQueryfieldService.updateQueryfield(baseQueryfield);
            //刷新任务调度
            quartzScheduler.refreshJobTime(baseQueryfield.getServiceid());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    @RequestMapping("batchUpdateQueryfieldList")
    @ResponseBody
    public Integer batchUpdateQueryfieldList(@RequestBody List<BaseQueryfield> baseQueryfieldList) {
        Integer result = 0;
        try {
            result = baseQueryfieldService.batchUpdateQueryfieldList(baseQueryfieldList);
            //刷新任务调度
            //quartzScheduler.refreshJobTime(baseQueryfield.getServiceid());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * @return sql文
     * @description 通过服务查询sql文
     * @author guoyanfei
     * @date 2017/11/24
     */
    @RequestMapping("getQuerysql")
    @ResponseBody
    public String getQuerysql(HttpServletRequest request) {
        String txtsql = "";
        try {
            String serviceId = request.getParameter("serviceId");
            String serviceType = request.getParameter("serviceType");
            String grade = request.getParameter("grade");
            BaseQuerysql baseQuerysql = baseQuerysqlService.getBaseQuerysql(serviceId, serviceType, grade);
            if (baseQuerysql != null) {
                txtsql = baseQuerysql.getSqlcontent();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return txtsql;
    }

}
